const { writeFileSync } = require('fs');
const { resolveApp } = require('./resolve');
const { name, i18nAppName, i18nBundleName } = require(resolveApp('package.json'));

function copyEntry() {
  const i18nSourceAppName = i18nAppName ? i18nAppName : name;
  const i18nSourceBundleName = i18nBundleName ? i18nBundleName : undefined;
  // 主入口
  writeFileSync(
    resolveApp('src/entry.tsx'),
    `import { i18n } from '@seeyon/tools';

// M5上需要调用sdk的能力去获取userAgent
if (/m5shell/i.test(navigator.userAgent)) {
  (window as any).sdk = require('@seeyon/native-sdk').sdk;
}

// 先初始化i18n，然后import 'index.tsx'
new Promise((resolve, reject) => {
  i18n.init('${i18nSourceAppName}', resolve, reject, '${i18nSourceBundleName}');
})
  .then(() => {})
  .catch(() => {
    console.log('国际化资源加载不全');
  })
  .finally(() => {
    import('./index');
  });
`,
  );
  // 供模块联邦使用的主入口
  writeFileSync(
    resolveApp('src/app4Exposes.tsx'),
    `import React, { useState, useEffect } from 'react';
import { i18n } from '@seeyon/tools';
import Entry from './app';

// 先初始化i18n，然后再渲染app.tsx中的Entry
function Entry4Exposer(props: any) {
  const [i18nReady, setI18nReady] = useState<boolean>(false);
  useEffect(() => {
    new Promise((resolve, reject) => {
      i18n.init('${i18nSourceAppName}', resolve, reject, '${i18nSourceBundleName}');
    })
      .then(() => {})
      .catch((error: any) => {
        console.error('国际化资源加载失败：' + error);
      })
      .finally(() => {
        setI18nReady(true);
      });
  }, []);
  return i18nReady ? <Entry {...props} /> : null;
}

export default Entry4Exposer;
`,
  );
}

function generateBuildTime() {
  // 构建时间
  const buildTime = new Date().getTime();
  const buildTime4LocaleString = new Date().toLocaleString();
  writeFileSync(
    resolveApp('version.json'),
    `{"buildTime": "${buildTime}", "buildTime4LocaleString": "${buildTime4LocaleString}"}\n`,
  );
}

module.exports = { copyEntry, generateBuildTime };
